package com.lyf.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

@Component
public class PicUtil {


    public static String templatePath;

    @Value("${templatePath: ''}")
    public void setTemplatePath(String templatePath) {
        PicUtil.templatePath = templatePath;
    }

    /**
     * 读取模板
     * @param template
     * @param map
     * @return
     * @throws IOException
     * @throws TemplateException
     */
      private static String getTemplate(String template, Map<String,Object> map) throws IOException, TemplateException {
          Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
          //获取文件的相对路径  可在控制台打印查看输出结果
          String filePath = ResourceUtils.getFile("classpath:templates").getPath();
          System.out.println(filePath);
          // 获取模板根路径(jar包启动部署在linux无效)
          cfg.setDirectoryForTemplateLoading(new File(filePath));
          // 指定模板路径(通用)
          // cfg.setDirectoryForTemplateLoading(new File(templatePath));
          cfg.setDefaultEncoding("UTF-8");
          cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
          cfg.setLogTemplateExceptions(false);

          Template temp = cfg.getTemplate(template);
          StringWriter stringWriter = new StringWriter();
          temp.process(map, stringWriter);
          stringWriter.flush();
          stringWriter.close();
          String resutl = stringWriter.getBuffer().toString();
          return resutl;
      }

    /**
     * 渲染html为图片
     * @param template
     * @param map
     * @return
     * @throws Exception
     */
    private static BufferedImage parseHtml(String template, Map<String,Object> map) throws Exception {
        String html = getTemplate(template, map);
        byte[] bytes=html.getBytes();
        ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=factory.newDocumentBuilder();
        Document document=builder.parse(bin);
        Java2DRenderer renderer = new Java2DRenderer(document,300, 100);
        return renderer.getImage();
    }

    /**
     * html模板直接下载为图片
     * @param template
     * @param map
     * @param response
     * @throws Exception
     */
      public static void turnImage(String template, Map<String,Object> map, HttpServletResponse response) throws Exception {
          response.setContentType("image/png");
          response.setDateHeader("expries", -1);
          response.setHeader("Cache-Control", "no-cache");
          response.setHeader("Pragma", "no-cache");
          // jdk原生导出
          ImageIO.write(parseHtml(template, map), "png", response.getOutputStream());
      }


    /**
     * html模板保存为图片文件
     * @param template
     * @param map
     * @param file
     * @throws Exception
     */
      public static void turnImage(String template, Map<String,Object> map, String file) throws Exception {
          // 插件导出
          FSImageWriter imageWriter = new FSImageWriter();
          // 设置压缩率
          imageWriter.setWriteCompressionQuality(1.0f);
          imageWriter.write(parseHtml(template, map), file);
      }
  }